#include "brokenlinewig.h"
#include "ui_brokenlinewig.h"


BrokenLineWig::BrokenLineWig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::BrokenLineWig)
{
    ui->setupUi(this);

    setupRealtimeDataDemo(ui->customPlot);
    ui->customPlot->replot();

    //ui->checkBox_temp->setChecked(true);
    //ui->checkBox_hui->setChecked(true);


}

BrokenLineWig::~BrokenLineWig()
{
    delete ui;
}

void BrokenLineWig::setValue(const QString &name,const int &value)
{
    this->name = name;
    this->key = value;

    ui->namelabel->setText(name);
    ui->valuelabel->setText(QString::number(value));
}

void BrokenLineWig::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
    customPlot->addGraph(); // blue line
    customPlot->graph(0)->setPen(QPen(Qt::blue));
    customPlot->graph(0)->setName("temp");
    //customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
    //customPlot->graph(0)->setAntialiasedFill(false);
    customPlot->addGraph(); // red line
    customPlot->graph(1)->setPen(QPen(Qt::red));
    customPlot->graph(1)->setName("hui");
    //customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));


    customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    customPlot->xAxis->setDateTimeFormat("MM-dd hh:mm:ss");
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->xAxis->setTickStep(2);
    customPlot->axisRect()->setupFullAxesBox();

    // make left and bottom axes transfer their ranges to right and top axes:
    //connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
    //connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

    // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
    connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
    dataTimer.start(1000); // Interval 0 means to refresh as fast as possible
    customPlot->legend->setVisible(true);
}

time_t BrokenLineWig::convertToTimestamp(const QString &dateTimeStr)
{
    // 根据xAxis的日期格式设置解析格式
       QDateTime dateTime = QDateTime::fromString(dateTimeStr, "yyyy/M/d h:m");
       if (dateTime.isValid()) {
           return dateTime.toMSecsSinceEpoch() / 1000;
       } else {
           qDebug() << "Failed to parse the date-time string.";
           return -1;
       }
}



void BrokenLineWig::realtimeDataSlot()
{
    //key的单位是秒
    double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
    //qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);
    //使用随机数产生两条曲线
    double value0 = qrand() % 100;
    //double value1 = qrand() % 80;
//    if (ui->checkBox_temp->isChecked())
//        ui->customPlot->graph(0)->addData(key, value0);//添加数据1到曲线1
    //if (ui->checkBox_hui->isChecked())
        //ui->customPlot->graph(1)->addData(key, value1);//添加数据2到曲线2
    //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
    //才能起到想要的效果，可以调整这两个值，观察显示的效果。
    ui->customPlot->graph(0)->removeDataBefore(key-8);
    ui->customPlot->graph(1)->removeDataBefore(key-8);

    //自动设定graph(1)曲线y轴的范围，如果不设定，有可能看不到图像
    //也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围
    ui->customPlot->graph(0)->rescaleValueAxis();
    ui->customPlot->graph(1)->rescaleValueAxis(true);

    //这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
    //就把8调整为比较大到值，比如要显示60秒，那就改成60。
    //这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
    ui->customPlot->xAxis->setRange(key+0.25, 8, Qt::AlignRight);//设定x轴的范围
    ui->customPlot->replot();
}

void BrokenLineWig::on_onBtn_clicked()
{
    int key;
    QString startTime =  ui->dateTimeEdit->text();
    QString endTime =  ui->dateTimeEdit_2->text();
    qDebug() << startTime;
    qDebug() << endTime;
    time_t timeStart =  convertToTimestamp(startTime);
    qDebug() << timeStart;
    time_t timeEnd =  convertToTimestamp(endTime);
    qDebug() << timeEnd;
    if(ui->namelabel->text() == "温度")
    {
        key = 301;
    }
    else if (ui->namelabel->text() == "光照")
    {
        key = 303;
    }
    else if (ui->namelabel->text() == "湿度")
    {
        key = 302;
    }
    qDebug() << key;


    //发送JSON
    // 设置 "keys" 字段
    QJsonArray keysArray;
    keysArray << QJsonValue::fromVariant(static_cast<qint64>(timeStart)) << QJsonValue::fromVariant(static_cast<qint64>(timeEnd));
    //设置data字段
    QJsonObject dataObj;
    dataObj.insert("limit",keysArray);
    dataObj.insert("key",key);
    //设置总字段
    QJsonObject allObj;
    allObj.insert("type",4);
    allObj.insert("data",dataObj);



    // 序列化为JSON文档
    QJsonDocument doc(allObj);
    QByteArray data = doc.toJson(QJsonDocument::Compact);

    QMQTT::Message message;
    message.setTopic("/app/data/down");
    message.setPayload(data);
    qDebug() << data;
    GlobalVal::mqtt->publish(message);
}
//void BrokenLineWig::receiveHistoryData(int key, const QList<QPair<qint64, QString>>& historyData)
//{
//    // 清空原有数据
//    // 处理接收到的历史数据
//        for (const auto& pair : historyData) {
//            qint64 timestamp = pair.first;
//            QString valueStr = pair.second;
//            double value = valueStr.toDouble(); // 将 QString 转换为 double

//            // 将数据添加到 QCustomPlot 中
//            ui->customPlot->graph(0)->addData(timestamp, value);
//        }

//        // 重新绘制图表
//        ui->customPlot->replot();
//    // 重新绘制图表
//    ui->customPlot->rescaleAxes();
//    ui->customPlot->replot();
//}
